package com.busionline.wotu.baselibrary.navigation.bottom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.busionline.wotu.baselibrary.navigation.bottom.iterator.ITabIterator;

import java.util.ArrayList;
import java.util.List;



/**
 *底部导航栏菜单
 *@author woochen123
 *@time 2017/11/23 10:23
 *@desc
 */
public class TabBottomNavigation extends LinearLayout {
    private List<TabItemView> tabViewList;
    private int mCurrentIndex = -1;

    public TabBottomNavigation(Context context) {
        this(context, null);
    }

    public TabBottomNavigation(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabBottomNavigation(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 添加条目
     * @param tabIterator
     */
    public void addItem(ITabIterator tabIterator) {
        if (tabViewList == null) {
            tabViewList = new ArrayList<>();
        }
        int index = 0;
        while (tabIterator.hasNext()) {
            TabItemView tabItem = tabIterator.next();
            View tabView = tabItem.getTabView();
            tabViewList.add(tabItem);
            //添加到当前布局
            addView(tabView);
            //重新设置布局
            LayoutParams layoutParams = (LayoutParams) tabView.getLayoutParams();
            layoutParams.weight = 1;
            layoutParams.gravity = Gravity.CENTER;
            tabView.setLayoutParams(layoutParams);
            //设置点击事件
            setOnItemClick(tabView,index);
            index++;
        }
        //第一个条目设置为选中
        mCurrentIndex = 0;
        tabViewList.get(0).setSelected(true);


    }

    /**
     * 条目点击事件
     *
     * @param tabView
     * @param i
     */
    private void setOnItemClick(View tabView, final int i) {
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mItemClickListener != null) {
                    mItemClickListener.onItemClick(i);
                    //把之前的设置为未选中，当前的设置为选中
                    tabViewList.get(mCurrentIndex).setSelected(false);
                    mCurrentIndex = i;
                    tabViewList.get(mCurrentIndex).setSelected(true);
                }
            }
        });
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    private OnItemClickListener mItemClickListener;

    public OnItemClickListener getOnItemClickListener() {
        return mItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }
}
